<template lang="pug">
div
  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="出门证生成")
        div(
            slot="right"
            :class="{'save-disabled': !saveEnabled, active: saveEnabled}"
            @click="save"
            ) 保存

      ScanSearch(
          placeholder="单号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      div
        KSlotPair.one(k="单据类型" :slotWidth="slotWidth")
          DropDownList.dropdown-list(
              :curValue="curValue"
              :list="dropdownList"
              :forbid="forbidChangeType"
              @select="selectBillType"
              :style="{zIndex: '30'}"
              )
        KSlotPair.one(k="审核单位" :slotWidth="slotWidth")
          DropDownList.dropdown-list(
              :curValue="curAuditDept"
              :list="auditDeptList"
              @select="selectAuditType"
              :style="{zIndex: '29'}"
              )
        KSlotPair.one(k="经办人" :slotWidth="slotWidth")
          input(v-model="Operator")
        KSlotPair.one(k="车牌号" :slotWidth="slotWidth")
          input(v-model="PlateNumber")
        KSlotPair.one(k="出门原因" :slotWidth="slotWidth")
          DropDownList.dropdown-list(
              :curValue="curReason"
              :list="reasonList"
              @select="selectReason"
              :style="{zIndex: '28'}"
              )
        KSlotPair.one(k="出门时间" :slotWidth="slotWidth")
          div.date(
              @click="chooseDate('ThisDate')"
              ) {{ date.text }}


    AddTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        :addRowToFront="true"
        @delete-row="deleteRow"
        )

  mt-datetime-picker(
      :ref="date.picker"
      type="date"
      v-model="date.date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      :startDate="new Date()"
      @confirm="(value) => confirmDate(value)"
      )

</template>

<script>
import api from "$api"
import util from "$util"

/*
 * 日期不能早于今天
 * 列表有数据时不能改类型，有数据时可以改
 * 不允许重复单号
 * 保存时所有都必填, 不填的报错
 */
export default {
  data() {
    return {
      searchValue: "",
      isLoading: false,
      saveEnabled: false,

      loading: {
        search: false,
        save: false,
      },

      headList: [
        { field: "delete-row", title: "", checked: true },
        { field: "BillNo", title: "单据编号", checked: true },
        { field: "DeptCode", title: "领料部门编号", checked: true },
        { field: "DeptName", title: "领料部门名称", checked: true },
      ],
      body: {
        list: [],
      },

      date: {
        picker: "startDatePickerThisDate",
        text: "选择日期",
        valid: false,
      },

      slotWidth: "12rem",
      codeMap: {}, // 已扫描的单号，用来去重

      curValue: "退货",
      curValueId: 1,
      dropdownList: [
        { id: 1, name: "退货" },
        { id: 2, name: "小票" },
      ],

      curAuditDept: "物流公司",
      curAuditDeptId: "WL",
      auditDeptList: [
        { id: "WL", name: "物流公司" },
        { id: "WG", name: "奥铃工厂物流管理科" },
      ],

      curReason: "",
      curReasonId: "",
      reasonList: [],

      Operator: "",
      PlateNumber: "",
    }
  },
  computed: {
    forbidChangeType() {
      return this.body.list.length > 0
    },
  },

  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }
      if (this.codeMap[value]) {
        return
      }

      this.loading.search = true
      try {
        let data = await api.EntryCreationSearch({
          BillNo: value,
          BillType: this.curValueId,
        })
        this.body.list.push(data || {})
        this.codeMap[value] = true
        this.saveEnabled = true
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    async save() {
      if (this.loading.save) {
        return
      }
      if (this.body.list.length === 0) {
        return
      }

      if (this.curAuditDeptId === "") {
        util.Alert("审核单位没填")
        return
      }
      if (this.Operator === "") {
        util.Alert("经办人没填")
        return
      }
      if (this.PlateNumber === "") {
        util.Alert("车牌号没填")
        return
      }
      if (this.curReasonId === "") {
        util.Alert("出门原因没填")
        return
      }
      if (!this.date.valid) {
        util.Alert("出门时间没填")
        return
      }

      let BillNoList = []
      for (let item of this.body.list) {
        BillNoList.push(item.BillNo)
      }

      this.loading.save = true
      try {
        await api.EntryCreationSave({
          BillNoList,
          BillType: this.curValueId,
          AuditDept: this.curAuditDeptId,
          Operator: this.Operator,
          Reason: this.curReasonId,
          PlateNumber: this.PlateNumber,
          OutTime: this.date.text,
        })
        util.Toast("保存成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 选择单据类型
    selectBillType(option) {
      this.curValue = option.vTitle
      this.curValueId = option.v
    },
    // 选择审核类型
    selectAuditType(option) {
      this.curAuditDept = option.vTitle
      this.curAuditDeptId = option.v
    },
    // 选择出门原因
    selectReason(option) {
      this.curReason = option.vTitle
      this.curReasonId = option.v
    },

    // 点击选择日期
    chooseDate(name) {
      this.$refs[`startDatePicker${name}`].open()
    },
    // 确认选择日期
    confirmDate(value) {
      this.date.text = value.toLocaleDateString("zh-CN", value)
      this.date.valid = true
    },

    // 删除一行
    deleteRow(i) {
      let index = this.body.list.length - i - 1
      this.codeMap[this.body.list[index].BillNo] = false
      this.body.list.splice(index, 1)
      if (this.body.list.length === 0) {
        this.saveEnabled = false
      }
    },

    // 获取出门原因列表
    async getReasonList() {
      try {
        let list = await api.EntryCreationReasonList()
        for (var item of list) {
          this.reasonList.push({
            id: item.DetailCode,
            name: item.DetailValue,
          })
        }
      } catch(err) {
        this.$root.error(err)
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    this.registerScanner()
    this.getReasonList()
  },
}
</script>

<style lang="stylus" scoped>

.save-disabled
  color: grey500

.active:active
  active-color()

.table
  margin-top: 0.5rem
  scan-table()

.dropdown-list
  width: 100%

.date
  text-align: center
  width: 100%
  border: 1px solid grey500
  color: grey700

</style>
